package com.zrq.secondkill.service.impl;

import com.zrq.secondkill.service.CacheService;
import com.zrq.secondkill.service.LocalCacheService;
import com.zrq.secondkill.service.SimplelayeredCacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author zrq
 */
@Service
public class SimplelayeredCacheServiceImpl implements SimplelayeredCacheService {

    private static List<CacheService> cacheServiceList = null;

    final
    LocalCacheService localCacheService;

    final
    CacheService redisCacheService;

    public SimplelayeredCacheServiceImpl(LocalCacheService localCacheService, @Qualifier("redisCacheServiceImpl") CacheService redisCacheService) {
        this.localCacheService = localCacheService;
        this.redisCacheService = redisCacheService;
    }

    @PostConstruct
    public void init() {
        cacheServiceList=new ArrayList<>();
        cacheServiceList.add((CacheService) localCacheService);
        cacheServiceList.add(redisCacheService);
    }

    @Override
    public void setK(String key, Object value, long expire, TimeUnit timeUnit, int k) {
        if (k > cacheServiceList.size()) {
            k = cacheServiceList.size();
        }

        for (int i = 0; i < k; ++i) {
            CacheService cacheService = cacheServiceList.get(i);
            cacheService.set(key, value, expire, timeUnit);
        }

    }

    @Override
    public Object get(String key) {
        for (CacheService cacheService :
                cacheServiceList) {
            Object o = cacheService.get(key);
            if(o!=null){
                return o;
            }
        }
        return null;
    }
}
